//  A PVM machine emulator
//
//  main.c
//  PVM_emulator
//
//  Created by Pei Liu on 9/8/11.
//  Copyright 2011 BobbyL. All rights reserved.
//  @version 0.1 deal with file input

#include <stdio.h>
#include <stdlib.h>
#include "pvm.h"


int main (int argc, const char * argv[])
{
    //set system stack pointer
    sp = &reg[0];
    //set instruction pointer(pointer od code[])
    ip = 0;
    
    //input file
    FILE* fin;
    
    if (argc == 2) 
    {
        fin = fopen(argv[1], "r");
        if(!fin)
        {
            fprintf(stderr, FILE_CANT_OPEN_ERR, argv[1]);
            exit(3);
        }
        
        //load header
        fscanf(fin, "%d%d%d%d", &codesize, &beginstr, &strsize, &entrypoint);
        
        int temp, i;
        //read all code in
        for(i = 0; i < codesize; i++)
        {
            fscanf(fin, "%d", &temp);
            code[i] = temp;
        }
        
        for(i = 0; i < strsize; i++)
        {
        	fscanf(fin, "%d", &temp);
            data[beginstr + i] = temp;
        }
        
        fclose(fin);
    }
    else
    {
        printf("Usage: %s <filename>\n", argv[0]);
        exit(2);
    }
    
    printf("BEGIN PVM:\n");
    
    while (code[ip] != 36) 
    {
        int arg1 = code[ip + 1];
        int arg2 = code[ip + 2];
        
        instrction[code[ip]](arg1,arg2);
        
        //move to next instruction
        ip += 3;
    }
    
    //this stop!
    instrction[code[ip]](++ip,++ip);
  
}

